import os
import re
import pandas as pd
import numpy as np
import SimpleITK as sitk
from radiomics import featureextractor
import six

#定义需要提取的特征
def catch_features(imagePath, maskPath):
    if imagePath is None or maskPath is None:
        raise Exception('Error getting testcase!')

    settings = {}

    settings['binWidth'] = 25
    settings['sigma'] = [3, 5]
    settings['Interpolator'] = sitk.sitkBSpline
    settings['resampledPixelSpacing'] = [1, 1]
    settings['voxelArrayShift'] = 1000
    settings['normalize'] = True
    settings['normalizeScale'] = 100

    extractor = featureextractor.RadiomicsFeatureExtractor(**settings)
    print('Extraction parameters:\n\t', extractor.settings)

    extractor.enableImageTypeByName('LoG')
    extractor.enableImageTypeByName('Wavelet')
    extractor.enableAllFeatures()
    extractor.enableFeaturesByName(firstorder=['Energy', 'TotalEnergy', 'Entropy', 'Minimum', '10Percentile',
                                               '90Percentile', 'Maximum', 'Mean', 'Median', 'InterquartileRange',
                                               'Range', 'MeanAbsoluteDeviation', 'RobustMeanAbsoluteDeviation',
                                               'RootMeanSquared', 'StandardDeviation', 'Skewness', 'Kurtosis',
                                               'Variance', 'Uniformity'])
    extractor.enableFeaturesByName(shape=['VoxelVolume', 'MeshVolume', 'SurfaceArea', 'SurfaceVolumeRatio',
                                           'Compactness1', 'Compactness2', 'Sphericity', 'SphericalDisproportion',
                                           'Maximum3DDiameter', 'Maximum2DDiameterSlice', 'Maximum2DDiameterColumn',
                                           'Maximum2DDiameterRow', 'MajorAxisLength', 'MinorAxisLength',
                                           'LeastAxisLength', 'Elongation', 'Flatness'])

    print('Enabled filters:\n\t', extractor.enabledImagetypes)

    feature_cur = []
    feature_name = []

    result = extractor.execute(imagePath, maskPath)

    for key, value in six.iteritems(result):
        print('\t', key, ':', value)
        feature_name.append(key)
        feature_cur.append(value)



    return feature_cur, feature_name

#恶性
#image_dir = r'E:\lung\LIDC-IDRI-Preprocessing-master\exing'
#良性
image_dir = r'D:\le-nii\lxing3'
image_files = [file for file in os.listdir(image_dir) if re.match(r'\d+_NI\d+_slice\d+.nii', file)]
mask_files = [file for file in os.listdir(image_dir) if re.match(r'\d+_MA\d+_slice\d+.nii', file)]
save_file = []
slice_names = []

for image_file in image_files:
    image_id, _, slice_num = image_file[:-4].split('_')  # 提取图像ID和切片编号
    mask_file = [file for file in mask_files if file.startswith(image_id)][0]  # 找到对应的掩膜文件

    imagePath = os.path.join(image_dir, image_file)
    maskPath = os.path.join(image_dir, mask_file)

    save_curdata, feature_name = catch_features(imagePath, maskPath)
    if len(save_curdata) > 0:  # 检查是否成功提取到特征
        save_file.append(save_curdata)
        slice_name = f"{image_id}_NI{image_id}_slice{slice_num}"
        slice_names.append(slice_name)

save_file = np.array(save_file, dtype=object)

name_df = pd.DataFrame(save_file)
name_df.columns = feature_name  # 使用特征名称作为列名
name_df.insert(0, 'Slice Name', slice_names)  # 添加切片名称列
# 保存第一列
slice_name_col = name_df['Slice Name']

# 切片操作
name_df_subset = name_df.iloc[:, 37:]

# 将第一列重新插入到切片后的数据框中
name_df_subset.insert(0, 'Slice Name', slice_name_col)

# 将结果保存到 Excel 文件
writer = pd.ExcelWriter('l-pyradiomics-features.xlsx')
name_df_subset.to_excel(writer, index=False)
writer.save()

